#include "Gamefont.h"
#include <tchar.h>
#include <string.h>
#define NULLPTR ((char *)0)
//C++11 - nullptr

freetype::Gamefont::Gamefont() : tex(0), sampler(0), vbo(0), vao(0), currentsize(0), screen_h(0), screen_w(0)
{
	fprintf(stdout, "Font constructor\n");
}

//(const char* strTypeface, int iFontHeight, int iFontWeight
void freetype::Gamefont::CreateFontFT(const char* strTypeface, GLuint program, int point_size, int dpi)
{
	if (IntiliazeFont(strTypeface, point_size, dpi))
	{
		fprintf(stdout, "%s was loaded succesfully\n", strTypeface);
		return;
	}
	glyph.LogError();
}

void freetype::Gamefont::InitVboAndTexture()
{
	glUniform1i(uniform_tex, 0);
	glActiveTexture(GL_TEXTURE0);

	glGenTextures(1, &tex);
	glBindTexture(GL_TEXTURE_2D, tex);

	glGenSamplers(1, &sampler);
	glBindSampler(0, sampler);
	glSamplerParameteri(sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glSamplerParameteri(sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glSamplerParameteri(sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glSamplerParameteri(sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

	glGenBuffers(1, &vbo);
	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);
	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	glEnableVertexAttribArray(0);
}

void freetype::Gamefont::DrawTextFT(const char* strText, vec2 pos, vec2 scale, type alignement)
{
	/*
	for (const char *p = strText; *p; p++)
	{
		GetGlyph(*p);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_R8,
			currentglyph.bitmap_width, currentglyph.bitmap_rows,
			0, GL_RED, GL_UNSIGNED_BYTE, currentglyph.bitmap_buffer);

		float vx = pos.x + currentglyph.bitmap_left * scale.x;
		float vy = pos.y + currentglyph.bitmap_top * scale.y;
		float w = currentglyph.bitmap_width * scale.x;
		float h = currentglyph.bitmap_rows * scale.y;

		switch (alignement)
		{
		case type::ALIGN_CENTER:
			break;
		case type::ALIGN_LEFT:
			break;
		case type::ALIGN_RIGHT:
			break;
		default:
			break;
		}

		struct {
			float x, y, s, t;
		} data[6] = {
				{ vx, vy, 0, 0 },
				{ vx, vy - h, 0, 1 },
				{ vx + w, vy, 1, 0 },
				{ vx + w, vy, 1, 0 },
				{ vx, vy - h, 0, 1 },
				{ vx + w, vy - h, 1, 1 }
		};

		glBufferData(GL_ARRAY_BUFFER, 24 * sizeof(float), data, GL_DYNAMIC_DRAW);
		glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
		glDrawArrays(GL_TRIANGLES, 0, 6);

		// increment position /
		pos.x += (currentglyph.advance.x >> 6) * scale.x;
		pos.y += (currentglyph.advance.y >> 6) * scale.y;
	}
	*/
}

freetype::Gamefont::~Gamefont()
{
	fprintf(stdout, "Font destructor\n");
}